import React, { Component } from 'react';
import {
  StyleSheet, Text, View, ScrollView, Image, TouchableOpacity, TouchableWithoutFeedback, DeviceEventEmitter, TextInput,
} from 'react-native';
import produce from 'immer';
import { Icon } from 'native-base';
import theme from '../../../native-base-theme/variables';
import ZlstIcon from '../../../components/zlst-icons';
import { FormText } from '../../../components';
import { UtilToast } from '../../../utils/util-method';
import * as todoService from '../../../services/todo';
import * as incidentRequest from '../../../services/incidentRequest';

class changePartsMoreConfirm extends Component {
  static navigationOptions = {
    title: '零部件更换',
    headerStyle: { backgroundColor: theme.toolbarDefaultBg, borderBottomWidth: 0, elevation: 0 },
    headerTintColor: '#FFFFFF',
    headerTitleStyle: {
      fontWeight: 'bold',
      fontSize: 20,
      flex: 1,
      textAlign: 'center',
    },
    headerBackImage: (
      <ZlstIcon
        name="fanhui"
        size={24}
        color="white"
      />
    ),
    headerRight: <View />,
  }

  constructor(props) {
    super(props);
    this.state = {
      type: 0,
      check: true,
      data: {
        materialId: '',
        materialName: '',
        materialCode: '',
        lotCode: '',
        materialSpecModel: '',
        batchGranularity: 'BY_PIECE',
        supplierName: '',
        manufacturerName: '',
        inDate: '',
        outDate: '',
        num: '',
        photos: '',
        usableQty: '',
        isOneFlag: true,
        consumeUnit: '',
      },
      downPart: { lotCode: '', materialId: '', materialName: '', splitCode: '', splitItemId: '' },
      downParts: [],
      upParts: [],
    };
  }

  componentDidMount() {
    // this.initDatas({ lotCode: this.props.navigation.state.params.code });
    this.initData();
    DeviceEventEmitter.addListener('maintainChangeMoreParts', this.maintainChangeMoreParts);
  }

  componentWillUnmount() {
    DeviceEventEmitter.removeAllListeners('maintainChangeMoreParts');
  }

  maintainChangeMoreParts = (data) => {
    const list = this.state.upParts.filter((it) => (it.lotCode === data));
    if (list && list.length > 0) {
      UtilToast(`备件'${data}'已经扫描过`, 'danger');
    } else {
      this.queryData(data);
    }
    // this.queryData(data);
  }

  queryData = async (lotCode) => {
    const ajaxData = {
      lotCode,
    };
    try {
      DeviceEventEmitter.emit('showLoading', true);
      const list = await incidentRequest.getFindMmMaterialVo(ajaxData);
      DeviceEventEmitter.emit('showLoading', false);
      if (list.data) {
        this.setState(produce(draft => {
          if (list.resultCode === 0 && list.data !== null) {
            if (list.data.materialCode === draft.data.materialCode) {
              draft.upParts.push(list.data);
            } else {
              UtilToast('该备件不能放在已选位置', 'danger');
            }
          }
        }));
      } else {
        UtilToast('扫出的条码号没有对应的备件信息', 'danger');
      }
    } catch (error) {
      DeviceEventEmitter.emit('showLoading', false);
    }
  }

  initData = () => {
    this.setState(produce(draft => {
      const upPart = this.props.navigation.state.params.upPart;

      draft.downPart = this.props.navigation.state.params.downPart;
      draft.data.materialId = upPart.materialId;
      draft.data.materialName = upPart.materialName;
      draft.data.materialCode = upPart.materialCode;
      draft.data.lotCode = upPart.lotCode;
      draft.data.materialSpecModel = upPart.materialSpecModel;
      draft.data.supplierName = upPart.supplierName;
      draft.data.manufacturerName = upPart.manufacturerName;
      draft.data.inDate = upPart.inDate;
      draft.data.batchGranularity = upPart.batchGranularity;
      draft.data.outDate = upPart.outDate;
      draft.data.num = '1';
      draft.data.photos = upPart.photos;
      draft.data.usableQty = upPart.usableQty;
      draft.data.isOneFlag = upPart.isOneFlag;
      draft.data.consumeUnit = upPart.consumeUnit;
      draft.downParts = this.props.navigation.state.params.downParts;
      draft.upParts = this.props.navigation.state.params.upParts;
    }));
  }

  // initDatas = async () => {
  //   DeviceEventEmitter.emit('showLoading', true);
  //   const data = await todoService.findMmMaterialVo({ lotCode: this.props.navigation.state.params.code });
  //   DeviceEventEmitter.emit('showLoading', false);
  //   if (data) {
  //     this.setState(produce(draft => {
  //       draft.data.materialId = data.materialId;
  //       draft.data.materialName = data.materialName;
  //       draft.data.lotCode = data.lotCode;
  //       draft.data.materialSpecModel = data.materialSpecModel;
  //       draft.data.supplierName = data.supplierName;
  //       draft.data.manufacturerName = data.manufacturerName;
  //       draft.data.inDate = data.inDate;
  //       draft.data.outDate = data.outDate;
  //       draft.data.num = '1';
  //       draft.data.postion = 'location';
  //       draft.data.photos = data.photos;
  //     }));
  //   } else {
  //     UtilToast('扫出的条码号没有对应的备件信息', 'danger');
  //     this.props.navigation.goBack();
  //   }
  // }

  check = () => {
    const check = !this.state.check;
    this.setState({ check });
  }

  // 0 重新扫描 ；1 继续扫描 ；2 完成扫描
  toQrcode = (flag) => {
    if (flag === '0') {
      this.props.navigation.goBack();
      this.props.navigation.navigate({ routeName: 'Qrcode', params: { flag: 'part', equipObjType: this.props.navigation.state.params.equipObjType, equipmentId: this.props.navigation.state.params.equipmentId } });
    } else {
      // eslint-disable-next-line no-lonely-if
      // if (this.state.data.num <= this.state.data.usableQty) {
      //   this.props.navigation.goBack();
      //   if (flag === '1') {
      //     if (this.state.check) {
      //       DeviceEventEmitter.emit('maintainChangeParts', { upPart: { ...this.state.data, splitCode: this.state.downPart.splitCode, splitItemId: this.state.downPart.splitItemId, description: this.state.downPart.description  }, downPart: { ...this.state.downPart } });
      //     } else {
      //       DeviceEventEmitter.emit('maintainChangeParts', { upPart: { ...this.state.data, splitCode: this.state.downPart.splitCode, splitItemId: this.state.downPart.splitItemId, description: this.state.downPart.description  }, downPart: null });
      //     }
      //     this.props.navigation.navigate({ routeName: 'Qrcode', params: { flag: 'part', equipObjType: this.props.navigation.state.params.equipObjType, equipmentId: this.props.navigation.state.params.equipmentId } });
      //   } else if (flag === '2') {
      //     if (this.state.check) {
      //       DeviceEventEmitter.emit('maintainChangeParts', { upPart: { ...this.state.data, splitCode: this.state.downPart.splitCode, splitItemId: this.state.downPart.splitItemId, description: this.state.downPart.description }, downPart: { ...this.state.downPart } });
      //     } else {
      //       DeviceEventEmitter.emit('maintainChangeParts', { upPart: { ...this.state.data, splitCode: this.state.downPart.splitCode, splitItemId: this.state.downPart.splitItemId, description: this.state.downPart.description  }, downPart: null });
      //     }
      //   }
      // } else {
      //   UtilToast('更换数目不能大于库存数目', 'danger');
      // }

      // eslint-disable-next-line no-lonely-if
      // if (this.state.downParts.length <= this.state.data.usableQty) {
      // eslint-disable-next-line no-lonely-if
      if (flag === '1') {
        this.props.navigation.navigate({ routeName: 'Qrcode', params: { flag: 'maintainChangeMoreParts' } });
      } else if (flag === '2') {
        this.props.navigation.goBack();
        const upParts = this.state.upParts.map((it, index) => ({
          ...it,
          splitCode: this.state.downParts[index].splitCode,
          splitItemId: this.state.downParts[index].splitItemId,
          description: this.state.downParts[index].description,
          num: 1,
        }));

        if (this.state.check) {
          DeviceEventEmitter.emit('maintainChangeParts', { upParts, downParts: this.state.downParts });
        } else {
          DeviceEventEmitter.emit('maintainChangeParts', { upParts, downParts: null });
        }
      }
      // } else {
      //   UtilToast('更换数目不能大于库存数目', 'danger');
      // }
    }
  }

  render() {
    let source = { uri: 'nopic' };
    if (this.state.type === 1) {
      source = require('../../../../assets/images/no-pic.png');
    }

    const waitToScanLocNum = this.state.downParts.length - this.state.upParts.length;
    return (
      <View style={{ flex: 1, backgroundColor: theme.myPrimary }}>
        <ScrollView style={{ flex: 1, flexDirection: 'column' }}>
          <View style={styles.img_container}>
            <Image
              // onPress={() => this.props.onItemClick(item)}
              style={styles.image}
              resizeMode="contain"
              source={source}
              fadeDuration={0}
              onError={
                () => {
                  this.setState({
                    type: 1,
                  });
                }
              }
            />
          </View>
          <View style={{ padding: 5 }}>
            <FormText name="名称" value={this.state.data.materialName} />
            <FormText name="型号" value={this.state.data.materialSpecModel} />
            <FormText name="供应商" value={this.state.data.supplierName} />
            <FormText name="生产厂商" value={this.state.data.manufacturerName} />
            <FormText name="入库日期" value={this.state.data.inDate} />
            <FormText name="出库日期" value={this.state.data.outDate} />
            {/* <FormText name="库存数量" value={this.state.data.usableQty} /> */}
            <FormText name="更换数量" value={`${this.state.downParts.length}${this.state.data.consumeUnit}`} />
            {/* <View style={{ flexDirection: 'row', padding: 5, alignItems: 'center' }}>
              <View style={{ flex: 2 }}>
                <Text style={{ color: 'white', fontSize: theme.myNormalFontSize }}>更换数量</Text>
              </View>
              <View style={{ flex: 3, flexWrap: 'wrap', flexDirection: 'row', alignItems: 'center' }}>
                <TextInput
                  style={{ padding: 0, margin: 0, color: 'white', fontSize: theme.myNormalFontSize }}
                  onChangeText={(text) => this.setState(produce(draft => { draft.data.num = text; }))}
                  value={this.state.downParts.length}
                  keyboardType="numeric"
                  editable={false}
                />
                <Text style={{ color: 'white', fontSize: theme.myNormalFontSize }}>{this.state.data.consumeUnit}</Text>
              </View>
            </View> */}
            <FormText name={`批量换上信息${waitToScanLocNum > 0 ? `(${waitToScanLocNum}个待扫码位置)` : ''}`} />
            <View style={{ padding: 5 }}>
              {this.state.downParts && this.state.downParts.map((data, index) => (
                <Text style={{ color: this.state.upParts.length > index ? 'white' : 'red', marginBottom: 8 }}>
                  {`${index + 1}.${data.description}@${data.materialName} ${this.state.upParts.length > index ? this.state.upParts[index].lotCode : '待扫码位置'}`}
                </Text>
              ))}
            </View>
            <TouchableWithoutFeedback onPress={this.check}>
              <View style={styles.check_container}>
                <Icon
                  name="check"
                  type="MaterialIcons"
                  style={{ fontSize: 20, backgroundColor: this.state.check ? '#207aff' : 'white', borderRadius: 10, color: this.state.check ? 'white' : theme.myPrimary }}
                />
                <Text style={{ color: 'white', marginLeft: 10 }}>自动记录该位置原零部件换下信息</Text>
              </View>
            </TouchableWithoutFeedback>
            <View style={{ padding: 5 }}>
              {this.state.downParts && this.state.downParts.map((data, index) => (
                <Text style={{ color: 'white', marginBottom: 8 }}>
                  {`${index + 1}.${data.description}@${data.materialName} ${data.lotCode ? data.lotCode : '首次换下'}`}
                </Text>
              ))}
              {/* <Text style={{ color: 'white' }}>
                {`${this.state.downPart.description}@${this.state.downPart.materialName} ${this.state.downPart.lotCode ? this.state.downPart.lotCode : '首次换下'}`}
              </Text> */}
            </View>
            <View style={styles.button_container}>
              <TouchableOpacity style={styles.button} onPress={() => this.toQrcode('0')}>
                <Text style={{ color: 'white' }}>重新扫描</Text>
              </TouchableOpacity>
              {
                waitToScanLocNum > 0 ? (
                  <TouchableOpacity style={styles.button} onPress={() => this.toQrcode('1')}>
                    <Text style={{ color: 'white' }}>继续扫描</Text>
                  </TouchableOpacity>
                ) : (
                  <TouchableOpacity style={styles.button} onPress={() => this.toQrcode('2')}>
                    <Text style={{ color: 'white' }}>扫描完成</Text>
                  </TouchableOpacity>
                )
              }
            </View>
          </View>
        </ScrollView>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  check_container: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    margin: 5,
  },
  button_container: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 5,
    marginBottom: 5,
  },
  button: {
    backgroundColor: '#207aff',
    margin: 5,
    flex: 1,
    padding: 10,
    alignItems: 'center',
    justifyContent: 'center',
  },
  img_container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  image: {
    width: '100%',
    height: 200,
  },
});

export default changePartsMoreConfirm;
